package com.shockweb.common.security;

import java.security.GeneralSecurityException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * des对称加解密
 * @author: 彭明华
 * 2017年5月15日 下午2:44:43
 *
 */
public class Des {



    /**
     * 根据键值进行加密
     * @param src 原数据
     * @param key 密钥
     * @param index 从index之后的数据开始加密
     * @return byte[] 加密后的数据
     * @throws GeneralSecurityException
     */
    public static byte[] encryptDES(byte[] src, byte[] key, int index) throws GeneralSecurityException {
        int len = key.length;
        int count = len%8!=0?len/8+1:len/8;
        byte[] keys = new byte[count*8];
        for(int i=0;i<keys.length;i++){
            if(i<key.length){
                keys[i] = key[i];
            }else{
                keys[i] = 0;
            }
        }
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(keys);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(keys);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        return cipher.doFinal(src, index, src.length - index);
    }

    /**
     * Description 根据键值进行解密
     * @param data 加密后的数据
     * @param key 密钥
     * @param index 从index之后的数据开始解密
     * @return byte[] 解密后的数据
     * @throws GeneralSecurityException
     */
    public static byte[] decryptDES(byte[] data, byte[] key, int index) throws GeneralSecurityException {
        int len = key.length;
        int count = len%8!=0?len/8+1:len/8;
        byte[] keys = new byte[count*8];
        for(int i=0;i<keys.length;i++){
            if(i<key.length){
                keys[i] = key[i];
            }else{
                keys[i] = 0;
            }
        }
        // 生成一个可信任的随机数源 

        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");


        DESKeySpec desKeySpec = new DESKeySpec(keys);

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKeySpec);

        IvParameterSpec iv = new IvParameterSpec(keys);

        cipher.init(Cipher.DECRYPT_MODE, securekey, iv);
        return cipher.doFinal(data, index, data.length - index);

    }

}
